<?php
/**
 * 个人预约-订单
 *
 * User: kaikaic
 * Date: 2018/10/28
 * Time: 20:52
 */

namespace app\psy\controller;


use app\api\service\MainService;
use app\psy\service\AccountService;
use app\psy\service\ConsultantService;
use app\psy\service\OrderService;
use controller\BasicAdmin;
use service\ConfigService;
use think\Db;
use PHPExcel;

class Order extends BasicAdmin {

    protected $table = "PsyOrder";
    public function index() {
        $this->title = "预约";
        $query = array();
        $query['order_status'] = intval($this->request->get("order_status"));
        $db = Db::name($this->table);
        if ($query['order_status']) {
            $db->where(['order_status'=>$query['order_status']]);
        }
        return parent::listRecord($db, "", true);
    }
    /**
     * 预约确认
     *
     * return array('1'=>'预约中', '2'=>'已预约', '3'=>'已参检', '4'=>'已完成', '10'=>'已取消', '11'=>'预约失败');
     */
    public function confirm() {
        $id = intval($this->request->param('id'));
        if (empty($id)) {
            $this->error('参数错误，请稍候再试！');
        }

        $record = OrderService::getInstance()->find($id);
        if (empty($record)) {
            $this->error('记录不存在，请重新操作!');
        }

        if ($record['order_status'] != 1) {
            $this->error('状态错误，订单已处理！');
        }
        if ($record['pay_status'] != 2) {
            $this->error('状态错误，订单还没支付！');
        }

        if ($this->request->isGet()) {
            $account = AccountService::getInstance()->single(array('id'=>$record['account_id']));
            if (!$account) {
                $this->error('数据错误，没有这个用户！');
            }
            $record['user_name'] = $account['nick_name'];
            $record['mobile'] = $account['mobile'];
            return view('confirm', [
                'title'=>'预约确认',
                'vo'=>$record,
            ]);
        }

        if ($this->request->isPost()) {
            $verify = intval($this->request->post("ok"));
            $comment = trim($this->request->post("comment"));

            $status = 0;
            if ($verify == 1) {
                $status = 2;
            }else if ($verify == 2) {
                $status = 11;
            }
            if (!$status) {
                $this->error('参数错误，请稍候再试！');
            }

            $update = array();
            $update['order_status'] = $status;
            $update['comment'] = $comment;
            $result = OrderService::getInstance()->update($update, $id);
            if ($result) {
                $type = true;
                if ($status == 11) {
                    $type = false;
                }
                $record['comment'] = $update['comment'];
                $this->sendOrderMessage($record['account_id'], $record, $type);

                $this->success('操作完成！', '');
            }else {
                $this->error('操作失败，请稍候再试！');
            }
        }
    }

    /**
     * 列表数据处理
     */
    protected function _index_data_filter(&$data) {
        $size = count($data);
        $orderStatus = ConfigService::examOrderStatus();
        $orderPayStatus = ConfigService::examOrderPayStatus();
        for ($i=0; $i<$size; $i++) {
            $temp = $data[$i];
            $account = AccountService::getInstance()->single(array('id'=>$temp['account_id']));
            if (!$account) {
                $temp['user_name'] = "";

            }
            $consultant = ConsultantService::getInstance()->single(array('id'=>$temp['consultant_id']));
            if (!$consultant) {
                $temp['consultant_name'] = "";

            }
            $temp['user_name'] = $account['nick_name'];
            $temp['consultant_name'] = $consultant['name'];
            $temp['order_status_txt'] = $orderStatus[$temp['order_status']];
            $temp['pay_status_txt'] = $orderPayStatus[$temp['pay_status']];

            $data[$i] = $temp;
        }
        $this->assign('order_status', $orderStatus);
        $this->assign('pay_status', $orderPayStatus);
    }

    public function export(){
        if ($this->request->isGet()) {
            $orderStatus = ConfigService::examOrderStatus();
            $orderPayStatus = ConfigService::examOrderPayStatus();
            $gid =  $this->request->param('gid',0);
//            $mecList = MecService::getInstance()->listMec($gid);
            return view('export', [
                'title'=>'导出订单',
                'group_id'=>$gid,
                'order_status'=>$orderStatus,
                'pay_status'=>$orderPayStatus,
//                'mec_list'=>$mecList,
            ]);
        }
        $query = array();
//        $query['name'] = $this->request->get("name");
        $query['order_status'] = intval($this->request->get("order_status"));
//        $query['mec_id'] = intval($this->request->get("mec_id"));
        $query['order_sn'] = $this->request->get("order_sn");
//        $query['exam_idCard'] = $this->request->get("exam_idCard");
        $query['start_time'] = $this->request->get("start_time");
        $query['end_time'] = $this->request->get("end_time");
        $query['group_id'] = $this->request->get("group_id");

        $db = Db::name($this->table);
        if($query['group_id']==1){
            $db->where('group_id','gt',0);
        }else{
            $db->where('group_id',0);
        }

//        if ($query['name']) {
//            $db->whereLike("name", "%{$query['name']}%");
//        }
        if ($query['mec_id']) {
            $db->where(['mec_id'=>$query['mec_id']]);
        }
        if ($query['order_sn']) {
            $db->whereLike('order_sn','%'.$query['order_sn'].'%');
        }
        if ($query['order_status']) {
            $db->where(['order_status'=>$query['order_status']]);
        }
        if ($query['exam_idCard']) {
            $db->whereLike('exam_idCard','%'.$query['exam_idCard'].'%');
        }
        if ($query['start_time']) {
            $db->whereLike('exam_date','gt',$query['start_time']);
        }
        if ($query['end_time']) {
            $db->whereLike('exam_date','lt',$query['end_time']);
        }
        $excelRecords = $db->select();
        $this->doExportAction($excelRecords,$query['group_id'] );
    }


    /**
     * 数据导出
     * @param $excelRecords
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public function doExportAction($excelRecords,$gid) {
        $objExcel = new PHPExcel();
        $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');

        // 设置水平垂直居中
        $objExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        // 字体和样式
        $objExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10);
        $objExcel->getActiveSheet()->getStyle('A2:AB2')->getFont()->setBold(true);
        $objExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);

        // 第一行、第二行的默认高度
        $objExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30);
        $objExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);

        //设置某一列的宽度
        $objExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30);
        $objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
        $objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $objExcel->getActiveSheet()->getColumnDimension('D')->setWidth(50);
        $objExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
        $objExcel->getActiveSheet()->getColumnDimension('F')->setWidth(25);
        $objExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $objExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $objExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
        // 设置表头
        // 合并
        $objExcel->getActiveSheet()->mergeCells('A1:I1');
        $objActSheet = $objExcel->getActiveSheet(0);

        //设置excel的标题
        $objActSheet->setTitle('订单统计');
        $objActSheet->setCellValue('A1','订单统计');
        $objActSheet->setCellValue('A2','订单号');
        $objActSheet->setCellValue('B2','客户姓名');
        $objActSheet->setCellValue('C2','客户身份证号');
        $objActSheet->setCellValue('D2','医院');
        $objActSheet->setCellValue('E2','套餐名');
        $objActSheet->setCellValue('F2','企业名');
        $objActSheet->setCellValue('G2','下单时间');
        $objActSheet->setCellValue('H2','订单状态');
        $objActSheet->setCellValue('I2','体检报告');
        $row = -1;
        $baseRow = 3; //数据从N-1行开始往下输出 这里是避免头信息被覆盖

        $orderStatus = ConfigService::examOrderStatus();
        $orderPayStatus = ConfigService::examOrderPayStatus();
        $mecList = MecService::getInstance()->listMec($gid);
        for ($i=0; $i<count($excelRecords); $i++) {
            $temp = $excelRecords[$i];
            $examinfo = Db::name('exam_enterprise')->find($temp['enterprise_id']);
            $mec = MecService::getInstance()->single(array('id'=>$temp['mec_id']));
            if (!isset($mecList[$temp['mec_id']])) {
                continue;
            }
            $temp['mec_txt'] = $mecList[$temp['mec_id']];
            $setidarr = explode(",",$temp['set_id']);
            $temp['set_txt'] = '';
            foreach ($setidarr as $key){
                $set = MecSetService::getInstance()->single(array('id'=>$key));
                if (!$set) {
                    continue;
                }
                $temp['set_txt'] .= $set['name'];
            }
            // 是否有体检报告
            $temp['report'] = 0;
            $temp['reportvalue'] = '';
            $report = ReportService::getInstance()->single(array('order_sn'=>$temp['order_sn']));
            if ($report) {
                $temp['report'] = 1;
                $temp['reportvalue'] = $report['name'];
            }
            $temp['order_status_txt'] = $orderStatus[$temp['order_status']];
            $row = $baseRow + $i;
            $objExcel->getActiveSheet()->setCellValue('A'.$row, $temp['order_sn']);
            $objExcel->getActiveSheet()->setCellValue('B'.$row, $temp['exam_name']);
            $objExcel->getActiveSheet()->setCellValue('C'.$row, $temp['exam_idCard']);
            $objExcel->getActiveSheet()->setCellValue('D'.$row, $temp['mec_txt']);
            $objExcel->getActiveSheet()->setCellValue('E'.$row, $temp['set_txt']);
            $objExcel->getActiveSheet()->setCellValue('F'.$row, $examinfo['name']);
            $objExcel->getActiveSheet()->setCellValue('G'.$row, date('Y-m-d H:i',$temp['create_time']));
            $objExcel->getActiveSheet()->setCellValue('H'.$row, $temp['order_status_txt']);
            $objExcel->getActiveSheet()->setCellValue('I'.$row, $temp['reportvalue']);

        }
        // 输出
        $objExcel->setActiveSheetIndex(0);
        $fileName = "订单数据导出_" . date('Y-m-d') . ".xlsx";
        // type1: 保存文件
        // $objWriter->save($fileName);

        //type2: 输出
        header('Content-Type: applicationnd.ms-excel');
        header("Content-Disposition: attachment;filename={$fileName}");
        header('Cache-Control: max-age=0');
        $objWriter->save('php://output');
    }
    /**
     * 发送预约消息
     */
    private function sendOrderMessage($accountID, $order, $flag=true) {
        $accountinfo = AccountService::getInstance()->find($accountID);
        $consultinfo = ConsultantService::getInstance()->find($order['consultant_id']);

        $orderinfo = MainService::getOrderInfoByOrdersn($order['order_sn']);

        if ($flag === true) {
            if($orderinfo['type_txt']=='视频'){

                $title = "您的视频心理咨询预约已确认，请于".$order['order_time']." ".$order['order_periods']."，在安静无打扰、网络效果好的环境进行咨询。 【九州心理咨询】";

            }else{
                $title  = "您的地面心理咨询预约已确认，请于".$order['order_time']." ".$order['order_periods']."，准时到达预约地点（".$order['comment']."），迟到或者逾期不到都不退费。【九州心理咨询】";
            }
        }else {
            $title = "很遗憾，".$consultinfo['name']." 心理咨询师".$order['order_time']." ".$order['order_periods'].'预约失败，订单号为'.$order['order_sn'].' 【九州心理咨询】';
        }
        sendSms($accountinfo['mobile'],$title);
    }
}

